/**
 * @author litianyuan
 * @date   2014-12-18
 */
var basicUrl="http://ishangbin.com";//ajax首页
var indexUrl="http://ishangbin.com";//登录界面即主页
var role={"1000":"超级管理员","1001":"管理员","1002":"运营"};//之后要修改
var roleType={"1000":{"1001":role["1001"],"1002":role["1002"]},"1001":{"1002":role["1002"]}};
var errorCodeJson={
'200':'成功',
'400':'客户端错误,请检查参数是否正确',
'500':'服务端错误',
'201':'用户已经绑定过该类型的sns账号',
'202':'该sns账号已经被别的用户绑定了',
'403':'字典项已经存在',
'402':'字典名称已经存在',
'404':'字典项code已经存在',
'401':'字典助记符已经存在',
'405':'没有查询到数据',
'4500':'数据非法',
'4540':'账号已被停用,请联系上宾客服',
'4544':'缺少必需参数',
'4545':'不支持该请求方式',
'4546':'不支持该类型的content-type',
'4200':'未关注',
'4201':'重复关注',
'4211':'会员不存在',
'4212':'已经是会员身份',
'4220':'非法卡',
'4221':'卡已被绑定',
'4222':'卡已被注销',
'4223':'卡不存在',
'4224':'卡未激活',
'4225':'卡已被停用',
'4226':'卡已被锁定',
'4230':'积分已被锁定',
'4240':'与预留信息不一致',
'4100':'帐号不存在',
'4101':'用户名与密码不匹配',
'4102':'旧密码不匹配',
'4103':'账号已被占用',
'4104':'账号已被修改',
'4105':'手机号被占用',
'4106':'手机号不存在',
'4107':'手机号码不匹配',
'4121':'验证码不匹配',
'4122':'验证码已过期',
'4130':'用户未登录',
'4131':'用户被锁定',
'4132':'非法用户',
'4133':'用户权限不足',
'4140':'登录错误',
'4141':'登录超时',
'4302':'您输入的商户名称已存在，请重新输入',
'4303':'您输入的商户编号已存在，请重新输入',
'4310':'该门店已存在店长，请勿重复添加',
'4320':'您输入的桌号不存在，请咨询服务员',
'4330':'当前设备无法识别，请联系系统管理员',
'4331':'您输入的激活码不准确',
'4332':'您输入的激活码已被使用，请输入未使用的激活码',
'4350':'您所在的门店的服务已停用，请联系系统管理员',
'4351':'商户未联网，请直接联系服务员',
'4334':'会员等级超出限制，最多仅允许5级',
'4500':'参数非法',
};
var authed={
	"1001":"未认证",
	"1002":"已认证",
	"1003":"认证审核中",
	"1004":"关闭审核中",
	"1005":"关闭"
};
var textCheckJson={
	"name": /^[a-zA-z]{1}[a-zA-Z0-9]{5,15}$/,//用户名检测，6-16位，字母开头
	"password":/^[\w]{8,20}$/,//密码检测，8-20位，不为空
	"telephone":/^0[1-9]{2,3}-?[2-9][0-9]{6,7}(-?[0-9]{1,4})?|1[0-9]{10}$/,//电话，固话及手机
	"phone": /^1\d{10}$/,//手机
	"tel": /^[1-9]{2,3}-?[2-9][0-9]{6,7}(-?[0-9]{1,4})?$/,//固话
	"nickname":/^[\u4e00-\u9fa5\w\S]{2,20}$/,//昵称，不含空格及特殊字符，2-20
	"dictCode": /^[0-9]{2,10}$/,//字典代码。2-10位数字
	"dictText":/^[\u4e00-\u9fa5\w]{1,20}$/,//字典文本，1-20汉字字符
	"dictName": /^[\u4e00-\u9fa5]{2,10}$/,//字典名，汉字
	"dictMnemonic": /^[a-zA-Z_]{2,20}$/,//字典助记符
	"shopcode":/^[a-zA-Z0-9]{1,20}$/,
	"float-regex": /^\-?\d+((\.|\,)\d+)?$/, //浮点数
}
var textCheckErrorJson={//
	"name":"必须以字母开头，不得含有汉字及其他符号",//用户名检测，5-16位，字母开头
	"password":"不能含有空格",//密码检测，8-20位，不为空
	"telephone":"请输入正确电话号码",//电话，固话及手机
	"phone": "请输入正确电话号码",//手机
	"tel": "请输入正确电话号码",//固话
	"nickname":"不能含有空格及特殊字符",//昵称，不含空格及特殊字符，2-20
	"dictCode":"只能为数字",//字典代码。2-10位数字
	"dictText":"只能为汉字",//字典文本，1-20汉字字符
	"dictName":"只能为汉字",//字典名，汉字
	"dictMnemonic":"只能输入下划线及英文",//字典助记符
	"shopcode":"只能输入英文及数字"
}

var constUrlDict={
	//员工管理类
	"staffs-base":"/staffs",
	"login":"/staffs/login",
	"logout":"/staffs/logout",
	"staff":"/staffs/staff",
	"staffs-shop":"/staffs/shop",
	"staffs-keeper":"/staffs/keeper",
	"staffs-password":"/staffs/password",
	//顾客管理类
	"customer":"/customer",
	"memberGrade":"/memberGrade",
	//顾客权益
	"benefit":"/benefit",
	"coupon":"/coupon",
	//桌台
	"tables":"/tables",
	"tables-batch":"/tables/batch", //批量添加桌台
	"tables-box":"/tables/box",
	"tables-table":"/tables/table",
	"tables-shop":"/tables/shop",
	//营业时间
	"businesstimes":"/businesstimes",
	"businesstime":"/businesstimes/businesstime",
	//活动
	"activity":"/activity",

};

//券领取重复策略
var obtainRepeatCategory = [
	{id:"AFTER_CHECK", name:"核销后可重领"},
	{id:"UNLIMITED", name:"无限制"},
];

//活动日期类型
var dateRangeCategory = [
	{type:'PERMANENT',name:'永久有效'},
	{type:'CONTINUOUS',name:'连续有效'},
	{type:'SELECTED_DATES',name:'手动选择'},
	// {type:'AUTOMATIC_DAY_DELAY',name:'延期生效'},
	// {type:'AUTOMATIC_MONTH_DELAY',name:'月底有效'},
	{type:'MONTH_EFFECTIVE',name:'当月有效'},
	{type:'EXCLUDE_MONTH_DAYS',name:'按月排除'},
	{type:'EXCLUDE_WEEKLY_DAY',name:'按周排除'},
	{type:'AROUND_FIX_DATE',name:'生日'},
	{type:'INCLUDE_WEEKLY_DAY',name:"按周指定"},
	{type:'INCLUDE_MONTH_DAYS',name:"按月指定"},
];

//活动日期类型
var couponRangeCategory = {
	CONTINUOUS:'连续有效',
	AUTOMATIC_DAY_DELAY:'延期生效',
	AUTOMATIC_MONTH_DELAY:'月底有效',
};

//活动类型
var ruleCategory=[
		{id:"DISCOUNT", name:"打折"},
		{id:"SPECIAL_PRICE", name:"特价"},
		{id:"COUPON", name:"消费返券"},
		{id:"COUPONFREE", name:"送券"},
		{id:"POINT", name:"积分"},
		{id:"POINTCONSUME", name:"积分抵现"},
		{id:"CHARGE", name:"充值"},
		{id:"CHARGECONSUME", name:"使用充值卡"},
];
//所有活动类型
var allRuleCategory={
		DISCOUNT:"打折",
		SPECIAL_PRICE:"特价",
		COUPON:"消费返券",
		COUPON_CONSUME:"消费用券",
		COUPONFREE:"送券",
		POINT:"积分",
		POINTCONSUME:"积分抵现",
		CHARGE:"充值",
		CHARGECONSUME:"使用充值卡",
		WELFARE:"福利",
};
//共享活动对应关系
var sharedActivitys={
	DISCOUNT:["POINT","COUPON"],
	SPECIAL_PRICE:["DISCOUNT","POINT","COUPON"],
	COUPON_CONSUME:["COUPON","POINT","CHARGECONSUME"],
	POINTCONSUME:["COUPON","POINT","CHARGECONSUME"],
	COUPON:['POINT'],
	POINT:['COUPON'],
	CHARGECONSUME:['POINT','COUPON'],
};


var shopTypeJson={
	1003:"加盟店",
	1001:"连锁店",
	1002:"自营店"
}
function ajaxSendFn(j,u,h,l){
//json,url,http,l
//传入数据，提交地址，提交方法，是否加JSON CONTENT-TYPE
	var redata;
	$.ajax({
		url:basicUrl +u,
		data: j,
		type: h,
		dataType:"json",
		async: false,
		beforeSend: function(xhr){
			if(l==1){//
				xhr.setRequestHeader( "Content-Type","application/json");
			}
			},//这里设置header
		success: function(data) {
			if(l!=2){
				if(data.code==4140)	location.href = indexUrl;
			}
			redata=data;
		},loading:function (){}
		});
	return redata;
}
function ajaxSendFn2(j,u,h,l){
//json,url,http,l
//传入数据，提交地址，提交方法，是否加JSON CONTENT-TYPE
	var redata;
	$.ajax({
		url:basicUrl +u,
		data: j,
		type: h,
		dataType:"json",
		beforeSend: function(xhr){
			if(l==1){//
				xhr.setRequestHeader( "Content-Type","application/json");
			}
			},//这里设置header
		success: function(data) {
			if(l!=2){
				if(data.code==4140)	location.href = indexUrl;
			}
			redata=data;
		},loading:function (){}
		});
	return redata;
}
function arrRemoveNullFN(a){//去除数组内空值
	var b=[];
	$.each(a, function(i,v) {
		if(v!="" && v!=null && v) b.push(v);
	});
	return b;
}
function arrToObj(a,b,c){//数组转对象
	var tem={};
	for(i=0,j=a.length;i<j;i++){
		if(!c) tem[a[i][b]]=a[i];
		else tem[a[i][b]]=a[i][c];
	}
	return tem;
}
function obj2Array(a,b){//对象根据特定key转数组
	var tem=[];
	for(var x in a)	{
		if(b) tem.push(a[x][b]);
		else tem.push(a[x]);
	}
	return tem;
}
function in_array(stringToSearch, arrayToSearch) {//in_array
 for (s = 0; s < arrayToSearch.length; s++) {
  thisEntry = arrayToSearch[s].toString();
  if (thisEntry == stringToSearch)  return true;
 }
 return false;
}

 //拼接网址
 function concatUrl(base, url){
	if(url !== ""){
		return base + "/" + url;
	}else{
		return base;
	}
}
//拼接参数
var mergeParam = function (param) {
	var arr = [];
	angular.forEach(param, function (value, key) {
		arr.push(key+'='+value);
	});
	return arr.join('&');
}
//转换时间,可以转日期字符串或是日期
var parseDate = function (date) {
	if (date) {
		var tmp;
		if (typeof(date) === "string") {
			tmp = new Date();
			var ms = Date.parse(date);
			tmp.setTime(ms);
		}else {
			tmp = date;
		}
		return tmp;
	}
}

// 思路：获取没重复的最右一值放入新数组
function unique(array){
  var r = [];
  for(var i = 0, l = array.length; i < l; i++) {
    for(var j = i + 1; j < l; j++)
      if (array[i] === array[j]) j = ++i;
    r.push(array[i]);
  }
  return r;
}

//显示错误信息
function errorMsg(result) {
	if (result) {
		var msg;
		if(result.code && result.message){
			msg = "错误:" + result.code + ", " + result.message;
		}else if (result.code) {
			msg = "错误:" + result.code + ", " + errorCodeJson[result.code];
 		}else{
			msg = "出错了!";
		}
		alert(msg);
	}
}

var app=angular.module('app',['ngRoute','720kb.tooltips','ngMessages','angular-loading-bar','ngAnimate',"ui.bootstrap"]);//创建APP

app.run(function($rootScope,$location,$interval,$filter,$http){//APP通用方法
	$rootScope.cache={};
	$rootScope.config={//设置
		time:new Date(),
		shopname:$.cookie("shopname")+"管理系统",
		breadset:{},
		slide:"",
		modalcontent:"",
		textCheckJson:textCheckJson,
		textCheckErrorJson:textCheckErrorJson,
	};
	$http.get(basicUrl+constUrlDict["staff"]).success(function (a) {
		if(a.code!=200){
			errorMsg(a);
		 location.href=indexUrl;}
		$rootScope.config.staff=a.result;
	});
	$interval(function() {//更新时间
	  $rootScope.config.time=new Date()
	}, 1000);
	$rootScope.urlFn=function(){//URL换算
		if(!$location.$$path){//
			$rootScope.active="shops";
			return;
		}
		localurl=$location.$$path.split("/");
		if(localurl[1]==""){//验证空
			localurl[1]="shops";
		}
		$rootScope.active=localurl[1];
	};
	$rootScope.urlFn();
	$rootScope.goto=function(url){	//转跳
		$location.path("/"+url);
		$rootScope.urlFn();
	}
	$rootScope.logout=function(){//登出
		logoutre=ajaxSendFn({},constUrlDict["logout"],"POST");
		$.cookie("shopname",null,{path:"/"});
		$.cookie("token",null,{path:"/"});
		if(logoutre.code==200){//
			location.href=indexUrl;
		}
	}
})


app.directive("dyName", [
		function() {
		  return {
			require: "ngModel",
			link: function(scope, elm, iAttrs, ngModelCtr) {
			  ngModelCtr.$name = scope.$eval(iAttrs.dyName)
			  var formController = elm.controller('form') || {
				$addControl: angular.noop
			  };
			  formController.$addControl(ngModelCtr);
			  scope.$on('$destroy', function() {
				formController.$removeControl(ngModelCtr);
			  });
			}
		  };
		}
	  ])
app.filter("ltdate",function(){//
		return function(d){//
			if(!d) return;
			 return 	new Date(Date.parse(d.replace(/-/g, "/")));
		}
})
app.filter("ltnumber",function(){//
		return function(d){//
			return parseInt(d);
		}
})

//按固定长度分隔字符串， length指定分隔长度,默认为4, separator指定分隔符,默认为"——"
app.filter("splitcode", function  () {
	return function (str, length, separator) {
		var arr = [];
		var len = length || 4;
		for (var i = 0; i < str.length; i = i + len) {
			var sstr = str.substr(i, len);
			arr.push(sstr);
		};
		return arr.join(separator||"-");
	}
})

//按长度(len)截取字符串，并附加...后缀
app.filter("substr", function () {
	return function (str,len) {
		if (str && str.length > len) {
			return str.substr(0,len)+'...';
		}
		return str;
	}
})

app.factory("tyAjaxFactory",function ($http) {
	var sevice={};
	sevice.get=function(n,a,b,c) {
		var result;
		$http({
			method:'GET',
			url:basicUrl+b,
			}).success().then(function (date) {
				result=date.data;
				$scope.cache={n:result};
			});
	}
	return sevice;
});
app.factory("tyFnFactory",function ($http,tyAjaxFactory) {
	var sevice={};
	sevice.shop=function(a) {
	return	tyAjaxFactory.get(a,{},"/shops");
	}
	return sevice;
});


app.directive('backButton', function(){
	return {
	  restrict: 'A',
	  link: function(scope, element, attrs) {
		element.bind('click', goBack);
		function goBack() {
		  history.back();
		  scope.$apply();
		}
	  }
	}
});

app.directive('countDown', function ($interval) {
	return {
		scope: {
			repeats: '=',
		},
		restrict: 'A',
		link: function (scope, element, attrs) {
			element.bind('click', countdown);
			function countdown(){
				var numdown = scope.repeats;
				var oldval = element.val();
				var timer = $interval(function(){
					element.attr('disabled', true);
					element.val(numdown--+"秒后再试");
				}, 1000, scope.repeats);

				timer.then(function () {
					element.val(oldval);
					element.attr('disabled', false);
				},function () {
					element.val("error...");
				});

				scope.$on("$destroy", function (event) {
					$interval.cancel(timer);
				});
			}
		}
	}
});

app.directive('inPut', function(){
	return {
	  restrict: 'EA',
	  scope:{age: '@dateType'},
	  link: function(scope, element, attrs) {
	  }
	}
});
app.factory('SearchSettingService',
    ['$http', '$q', function($http, $q) {
    return {
        setting: function() {
            var deferred = $q.defer();
            $http.get(basicUrl+'/shops').success(function(result) {
                deferred.resolve(result);
            }).error(function(result) {
                deferred.reject("network error");
            });

            return deferred.promise;
        }
    };
}]);
